import Vue from 'vue'
import Vuex from 'vuex'
import http from '../config/http'
import { User, Token } from '@/storage/'
import { isReallyNull } from '../common/util'
Vue.use(Vuex)
const account = uni.getAccountInfoSync()
const store = new Vuex.Store({
  state: {
    hasLogin: false,
    loginProvider: '',
    userInfo: null,
    openid: null,
    testvuex: false,
    colorIndex: 0,
    account:account,
    colorList: ['#FF0000', '#00FF00', '#0000FF']
  },
  getters: {
    userPhone: (state) => {
      if (state.userInfo) {
        return state.userInfo.phone
      } else {
        return null
      }
    },
    currentColor (state) {
      return state.colorList[state.colorIndex]
    },
    needAuthUserInfo(state) {
      if ((!isReallyNull(state.userInfo))&&isReallyNull(state.userInfo.nickName)&&isReallyNull(state.userInfo.avatarUrl)) {
        return true
      } else {
        return false
      }
    },
    isSystemUser(state) {
      if (state.userInfo) {
        return state.userInfo.systemUser
      } else {
        return false
      }
    },
  },
  mutations: {
    login (state, provider) {
      state.hasLogin = true
      state.loginProvider = provider
    },
    logout (state) {
      state.hasLogin = false
      state.openid = null
    },
    setOpenid (state, openid) {
      state.openid = openid
    },
    setTestTrue (state) {
      state.testvuex = true
    },
    setTestFalse (state) {
      state.testvuex = false
    },
    setColorIndex (state, index) {
      state.colorIndex = index
    },
    setUserInfo(state,userInfo) {
      state.userInfo=userInfo
    }
  },
  actions: {
    // lazy loading openid
    wxlogin: async ({ commit, state }) => {
      return await new Promise((resolve, reject) => {
        resolve()
        return
        if (!isReallyNull(Token.Get())) {
          commit('setUserInfo', User.Get())
          commit('login')
          resolve()
        } else {
          uni.login({
            success: data => {
              const appid = state.account.miniProgram.appId
              http.get(`/wx/user/${appid}/login`, { code: data.code }, false)
                .then(res => {
                  if (res.success) {
                    Token.Set(res.data.token)
                    User.Set(res.data)
                    commit('setUserInfo',User.Get()) 
                    commit('login')
                    resolve(res)
                  }
                })
            },
            fail: err => {
              console.log(
                'uni.login 接口调用失败，将无法正常使用开放接口等服务',
                err
              )
              reject(err)
            }
          })
        }
      })
    },
    wxgetPhone({ commit, state }, eAction) {
      const appid = state.account.miniProgram.appId
      let detail = eAction.detail
      return new Promise((resolve, reject) => {
        if (detail.errMsg == 'getPhoneNumber:ok') {
          http.post(`/wx/user/${appid}/phone`, detail, false)
            .then(res => {
              if (res.success) {
                Token.Set(res.data.token)
                User.Set(res.data)
                commit('setUserInfo', res.data)
                resolve(res.data.phone)
              } 
            }).catch(err => {
              reject(err)
            })
        }
      })
    },
    bindPhone({ commit, state }, data) {
      return new Promise((resolve, reject) => { 
        http.post('/wx/appletuser/bind',data).then((res)=>{
          if(res.success){
            Token.Set(res.data.token)
            User.Set(res.data)
            commit('setUserInfo', res.data)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    unbundlingPhone({ commit, state }) {
      return new Promise((resolve, reject) => { 
        http.get('/wx/appletuser/unbind').then((res)=>{
          if(res.success){
            Token.Set(res.data.token)
            User.Set(res.data)
            commit('setUserInfo', res.data)
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    wxgetUserInfo({ commit, state }, eAction) {
      const appid = state.account.miniProgram.appId
      let detail = eAction.detail
      return new Promise((resolve, reject) => {
        if (detail.errMsg == 'getUserInfo:ok') {
          User.Update(detail.userInfo)
          http.post(`/wx/user/${appid}/info`, detail, false)
            .then(res => {
              if (res.success) {
                Token.Set(res.data.token)
                User.Update(res.data)
                commit('setUserInfo', res.data)
                resolve(res.data)
              } 
            }).catch(err => {
              reject(err)
            })
        }
      })
    }
  }
})

export default store
